package com.sunlord.utils;

import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.enums.UnitType;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Settings.BizDbConnectionConfig;
import com.h3bpm.base.util.AppUtility;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 获取其他数据库连接参数
 * @author AUTH zhengyj
 * 2018-09-30
 */
public class DbConfigUtil extends ControllerBase {
    @Override
    public String getFunctionCode() {
        return null;
    }

    public static BizDbConnectionConfig DBConfig = null;

    public static List<Unit> unitList = null;

    public static BizDbConnectionConfig getDBConfigByCode(String code) {

        try {
            DBConfig = AppUtility.getEngine().getSettingManager().GetBizDbConnectionConfig(code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DBConfig;
    }

    public static List<Unit> getAllUnit(UnitType unitType){
        try {
            unitList =  AppUtility.getEngine().getOrganization().GetAllUnits(unitType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unitList;
    }


    /**
     * 获取连接
     * @param className
     * @param dbCode
     * @return
     */
    public static Connection getConn(String className,String dbCode)
    {
        Connection connection = null;
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {

        }
        getDBConfigByCode(dbCode);
        try {
             connection = DriverManager.getConnection(DBConfig.getDbConnectionString(), DBConfig.getUserName(), DBConfig.getPassword());
        } catch (SQLException e) {

        }
        return connection;
    }

    /**
     * 关闭连接
     * @param conn
     */
    public static void closeConn(Connection conn) {
        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("关闭连接失败！");
                //e.printStackTrace();
            }
        }
    }




}

